<template>
  <div>
    <img src="../assets/bg.jpg" alt="" class="headerimg">
    <cube-form :model='model' :schema='schema' @submit='submitHandler'></cube-form>
  </div>
</template>
<script>
export default {
  data: function() {
    return {
      model: {
        username: '',
        password: ''
      },
      schema: {
        fields: [
          //用户名配置
          {
            type: 'input',
            modelKey: 'username',
            label: '用户名',
            props: {
              placeholder: '请输入用户名'
            },
            rules: {
              //校验规则
              required: true,
              type: 'string',
              min: '1',
              max: '15'
            },
            trigger: 'blur', //失焦检测
            messages: {
              required: '用户名不能为空',
              min: '用户名不能少于1字符',
              max: '用户名不能大于15字符'
            }
          },
          {
            type: 'input',
            modelKey: 'password',
            label: '密码',
            props: {
              placeholder: '请输入密码',
              type: 'password',
              eye: {
                open: false
              }
            },
            rules: {
              //校验规则
              required: true
            },
            trigger: 'blur' //失焦检测
          },
          {
            type: 'submit',
            label: '登录'
          }
        ]
      }
    }
  },
  methods: {
    //es7 async await 异步请求
    async submitHandler(e){
      e.preventDefault()
      try{
        const result=await this.$http.get('/api/login', {params: this.model})
        if(result.data.code =='0'){
          //调用vuex存储token的方法
          this.$store.commit('settoken',result.data.token)
          //设置本地存储,因为vuex中数据刷新会丢失 
          window.localStorage.setItem('token',result.data.token)

          this.$router.replace({path: '/index'})
        }else{
          alert(result.data.message)

        }
      }catch{
        console.log(err)
      }
    }
  }
}
</script>
<style scoped>
  .headerimg{
    height: 150px;
    width: 100px
  }

</style>
